package com.gs.m_person_details

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationListener
import com.gs.common.BaseCompatActivity
import com.gs.common.constant.ActionConst
import com.gs.common.global.GlobalVariables
import com.gs.common.util.ActionBarUtil
import com.gs.common.util.LocationUtil
import com.gs.common.util.StringUtil
import com.gs.common.util.ToastUtil
import com.gs.m_person_details.databinding.PersonDetailsLayoutBinding
import pub.devrel.easypermissions.EasyPermissions

class PersonDetailsActivity: BaseCompatActivity(), View.OnClickListener, AMapLocationListener {

    private lateinit var binding: PersonDetailsLayoutBinding
    private lateinit var mLocationUtil: LocationUtil
    private lateinit var mLocationClient: AMapLocationClient
    private val mLoginUser = GlobalVariables.loginUser

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = PersonDetailsLayoutBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 加载定位工具
        mLocationUtil = LocationUtil()
        // 初始化定位
        mLocationClient = mLocationUtil.initLocation(this, this)
        // 启动定位
        mLocationUtil.startLocation(this)
        binding.locationOptionTv.addTextChangedListener {
            if (binding.locationOptionTv.text.equals("暂无定位")) {
                for (i in 1..10) {
                    mLocationUtil.startLocation(this)
                    if (!binding.locationOptionTv.text.equals("暂无定位")) {
                        break
                    }
                }
            }
        }

        // 设置自定义 action bar
        ActionBarUtil.setCustomActionBar(this, R.layout.person_details_actionbar_layout)

        // 设置返回键
        val backBtn = findViewById<ImageView>(R.id.back_btn)
        backBtn.setOnClickListener {
            finish()
        }

        setViewsOnClickListener()

    }

    override fun onResume() {
        super.onResume()
        if (mLoginUser == null) {
            ToastUtil.showShortToast(this, "用户登录状态已失效，请重新登录！")
            return
        }
        binding.nicknameOptionTv.text = mLoginUser.nickname
        binding.usernameOptionTv.text = mLoginUser.userName
        binding.phoneNumOptionTv.text = mLoginUser.phoneNumber
        binding.businessAuthorityTv.text = if (mLoginUser.isBusiness) {
            "已申请"
        } else {
            "未申请"
        }
    }

    private fun changeInfo(title: String, content: String) {
        val intent = Intent(this, ChangeInfoActivity::class.java)
        intent.putExtra("title", title)
        intent.putExtra("content", content)
        startActivity(intent)
    }

    private fun setViewsOnClickListener() {
        binding.nicknameOption.setOnClickListener(this)
        binding.usernameOption.setOnClickListener(this)
        binding.phoneNumOption.setOnClickListener(this)
        binding.businessAuthority.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when(v) {
            binding.nicknameOption -> changeInfo("昵称", mLoginUser?.nickname ?: "")
            binding.usernameOption -> changeInfo("用户名", mLoginUser?.userName ?: "")
            binding.phoneNumOption -> changeInfo("手机号", mLoginUser?.phoneNumber ?: "")
            binding.businessAuthority -> {
                val intent = Intent().apply {
                    action = ActionConst.TO_BUSINESS_AUTHORITY_ACTIVITY_ACTION
                }
                startActivity(intent)
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        // 设置权限请求结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onLocationChanged(p0: AMapLocation?) {
        if (p0 != null) {
            if (p0.errorCode == 0) {
                // 地址
                val address = p0.province + p0.city + p0.district
                val abbrAddress = address
                val currentAddress = findViewById<TextView>(R.id.location_option_tv)
                currentAddress.text = StringUtil.replaceEmptyString(abbrAddress, "暂无定位")
                mLocationClient.stopLocation()
            } else {
                Log.e(
                    "AmapError", "location Error, ErrCode:"
                            + p0.errorCode + ", errInfo:"
                            + p0.errorInfo
                )
            }
        }
    }

    fun restartLocationP(view: View) {
        mLocationUtil.startLocation(this)
    }
}